document.addEventListener('DOMContentLoaded', function() {
    // 创建浮动笔记窗口元素
    const notesContainer = document.createElement('div');
    notesContainer.id = 'float-notes-container';
    notesContainer.innerHTML = `
        <div id="float-notes-header">
            <span id="float-notes-title">学习笔记</span>
            <div id="float-notes-controls">
                <button id="float-notes-save" title="保存到本地文件">💾 保存</button>
                <button id="float-notes-minimize" title="最小化">−</button>
                <button id="float-notes-close" title="关闭">×</button>
            </div>
        </div>
        <div id="float-notes-content">
            <textarea id="float-notes-textarea" placeholder="在这里记录你的学习笔记或作为草稿本使用..."></textarea>
        </div>
        <div id="float-notes-resize-handle"></div>
    `;
    
    document.body.appendChild(notesContainer);
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        #float-notes-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 350px;
            height: 250px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            resize: both;
            min-width: 200px;
            min-height: 150px;
            border: 1px solid #ddd;
        }
        
        #float-notes-header {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            color: white;
            padding: 8px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: move;
            user-select: none;
        }
        
        #float-notes-title {
            font-weight: bold;
            font-size: 14px;
        }
        
        #float-notes-controls {
            display: flex;
            gap: 4px;
        }
        
        #float-notes-controls button {
            background: transparent;
            border: none;
            color: white;
            font-size: 14px;
            cursor: pointer;
            height: 24px;
            border-radius: 4px;
            padding: 0 6px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.2s;
        }
        
        #float-notes-controls button:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        
        #float-notes-content {
            flex: 1;
            overflow: hidden;
            padding: 10px;
        }
        
        #float-notes-textarea {
            width: 100%;
            height: 100%;
            border: none;
            resize: none;
            outline: none;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 14px;
            line-height: 1.5;
        }
        
        #float-notes-textarea:focus {
            border-color: #3498db;
        }
        
        #float-notes-resize-handle {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 12px;
            height: 12px;
            cursor: se-resize;
            background: linear-gradient(-45deg, transparent 30%, #ccc 30%, #ccc 50%, transparent 50%);
        }
        
        #float-notes-container.minimized {
            height: 40px !important;
        }
        
        #float-notes-container.minimized #float-notes-content {
            display: none;
        }
        
        #float-notes-container.minimized #float-notes-resize-handle {
            display: none;
        }
        
        #float-notes-toggle-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #2c3e50, #3498db);
            color: white;
            border: none;
            border-radius: 50%;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            cursor: pointer;
            font-size: 24px;
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1001;
        }
    `;
    
    document.head.appendChild(style);
    
    // 添加浮动按钮（当笔记窗口被关闭时显示）
    const toggleButton = document.createElement('button');
    toggleButton.id = 'float-notes-toggle-btn';
    toggleButton.innerHTML = '✏️';
    toggleButton.title = '打开笔记窗口';
    document.body.appendChild(toggleButton);
    
    // 绑定事件
    bindNotesEvents();
    
    // 加载保存的笔记内容
    loadNotes();
});

function bindNotesEvents() {
    const container = document.getElementById('float-notes-container');
    const header = document.getElementById('float-notes-header');
    const saveBtn = document.getElementById('float-notes-save');
    const minimizeBtn = document.getElementById('float-notes-minimize');
    const closeBtn = document.getElementById('float-notes-close');
    const textarea = document.getElementById('float-notes-textarea');
    const toggleBtn = document.getElementById('float-notes-toggle-btn');
    
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;
    
    // 拖拽功能
    header.addEventListener('mousedown', dragStart);
    document.addEventListener('mouseup', dragEnd);
    document.addEventListener('mousemove', drag);
    
    function dragStart(e) {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
        
        if (e.target === header) {
            isDragging = true;
            container.style.cursor = 'grabbing';
        }
    }
    
    function dragEnd() {
        initialX = currentX;
        initialY = currentY;
        
        isDragging = false;
        container.style.cursor = 'default';
    }
    
    function drag(e) {
        if (isDragging) {
            e.preventDefault();
            
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;
            
            xOffset = currentX;
            yOffset = currentY;
            
            setTranslate(currentX, currentY, container);
        }
    }
    
    function setTranslate(xPos, yPos, el) {
        el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
    }
    
    // 保存到本地文件功能
    saveBtn.addEventListener('click', function() {
        const content = textarea.value;
        if (content.trim() === '') {
            alert('笔记内容为空，无需保存');
            return;
        }
        
        const date = new Date();
        const timestamp = date.toISOString().replace(/[:.]/g, '-').slice(0, 19);
        const filename = `freeRTOS-notes-${timestamp}.txt`;
        
        const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 100);
        
        // 给用户一个保存成功的反馈
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '✅ 已保存';
        setTimeout(() => {
            saveBtn.innerHTML = originalText;
        }, 2000);
    });
    
    // 最小化功能
    minimizeBtn.addEventListener('click', function() {
        container.classList.toggle('minimized');
        if (container.classList.contains('minimized')) {
            minimizeBtn.textContent = '+';
            minimizeBtn.title = '最大化';
        } else {
            minimizeBtn.textContent = '−';
            minimizeBtn.title = '最小化';
        }
    });
    
    // 关闭功能
    closeBtn.addEventListener('click', function() {
        container.style.display = 'none';
        toggleBtn.style.display = 'flex';
    });
    
    // 显示功能
    toggleBtn.addEventListener('click', function() {
        container.style.display = 'flex';
        toggleBtn.style.display = 'none';
    });
    
    // 自动保存功能
    textarea.addEventListener('input', function() {
        localStorage.setItem('floatNotesContent', textarea.value);
    });
}

function loadNotes() {
    const savedContent = localStorage.getItem('floatNotesContent');
    if (savedContent) {
        document.getElementById('float-notes-textarea').value = savedContent;
    }
}